package pile.pay.service.impl;

import cn.hutool.json.JSONUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import pile.pay.entity.*;
import pile.pay.mapper.ElectricpileMapper;
import pile.pay.service.IChargeOrderService;
import pile.pay.service.IElectricVersionService;
import pile.pay.service.IElectricpileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import pile.pay.service.IRechargeService;
import pile.pay.utils.RedisCache;
import pile.pay.utils.WebUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import pile.pay.params.electricpile.DeleDTO;
import pile.pay.params.electricpile.ListDTO;
/**
 * <p>
 * 电桩管理表 服务实现类
 * </p>
 *
 * @author 郭天义
 * @since 2024-06-28
 */
@Service
@Log4j2
public class ElectricpileServiceImpl extends ServiceImpl<ElectricpileMapper, Electricpile> implements IElectricpileService {

    @Autowired
    private ElectricpileMapper electricpileMapper;

    @Autowired
    private IRechargeService rechargeService;

    @Autowired
    private IChargeOrderService chargeOrderService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IElectricVersionService electricVersionService;



    /**
     * 现根据桩号查询出电桩
     */
    @Override
    public Electricpile selectByCode(String equipmentCode) {
        return electricpileMapper.selectByCode(equipmentCode);
    }



    /**
     * 查询是否有充电中的订单 发送新的余额给电桩
     *recharge
     * @param
     */
    @Override
    @Transactional
    public void updateChargingAccountBalance(Recharge recharge) {

        try {

            if (recharge == null) {
                return;
            }
            //拿到用户ID
            Integer memberId = recharge.getMemberId();
            //查询是否有正在充电的订单
            ChargeOrder chargeOrder = chargeOrderService.selectMemberChargingOrder(memberId);

            //判断是否有订单
            if (chargeOrder == null) {
                return;
            }
            //有充电中的订单 需要 更新电桩余额

            //查询配置 看是否是mq发送信息还是 ip发送
            String finalValue = ipAddress(chargeOrder.getEquipmentCode());
            if (finalValue == null) {
                return;
            }

            //修改redis的 充电余额

            Map<String, Object> cacheMap = redisCache.getCacheObject("startChargeSeq:" + chargeOrder.getStartChargeSeq());
            if (cacheMap == null) {
                return;
            }

            BigDecimal updateBalance = new BigDecimal(0);
            //判断订单的支付类型
            if (chargeOrder.getPaymentTypes() == 0 || chargeOrder.getPaymentTypes() == 6) {
                //余额
                BigDecimal balance = (BigDecimal) cacheMap.get("balance");

                updateBalance = balance.add(recharge.getRechargeAmount());
                cacheMap.put("balance", updateBalance);
            }

            if (chargeOrder.getPaymentTypes() == 1 || chargeOrder.getPaymentTypes() == 5) {
                //充电金
                BigDecimal chargingGold = (BigDecimal) cacheMap.get("chargingGold");

                updateBalance = chargingGold.add(recharge.getRechargeAmount()).add(recharge.getGiveAmount());
                cacheMap.put("chargingGold", updateBalance);
            }
            updateBalance = updateBalance.setScale(2, RoundingMode.HALF_UP);
            //修改redis里面的余额
            redisCache.setCacheObject("startChargeSeq:" + chargeOrder.getStartChargeSeq(), cacheMap, 2, TimeUnit.HOURS);

            //组装参数  发送给电桩
            HashMap<String, String> objectObjectHashMap = new HashMap<>();
            //电桩编码
            objectObjectHashMap.put("equipmentCode", chargeOrder.getEquipmentCode());
            //电枪号
            objectObjectHashMap.put("connectorCode", chargeOrder.getConnectorCode());
            //更新之后的余额
            objectObjectHashMap.put("updateBalance", String.valueOf(updateBalance));
            //流水号
            objectObjectHashMap.put("startChargeSeq", chargeOrder.getStartChargeSeq());

            //发送消息
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    //dispatchOrdersService.remoteAccountBalanceUpdate(objectObjectHashMap, finalValue);
                }
            });
        } catch (Exception e) {
            log.error("充电中充值给电桩发送更新命令报错:" + e);
        }

    }

    /**
     * 返回netty的IP地址
     *
     * @return
     */
    private String ipAddress(String equipmentCode) {

        //查询电桩版本 获取IP地址 先查询redis 如果没有查数据库
        String ipAddress = redisCache.getCacheObject("equipment:network:" + equipmentCode);
        log.info("查询redis的ip地址" + ipAddress);
        if (ipAddress == null) {
            //redis 不存在啊 查询数据库 根据电桩编码查询
            ElectricVersion electricVersion = electricVersionService.selectByEquipmentCode(equipmentCode);
            log.info("查询数据库数据:" + JSONUtil.toJsonStr(electricVersion));
            if (electricVersion == null) {
                log.info("电桩号:" + equipmentCode + "不存在IP地址");
                return null;
            }
            ipAddress = electricVersion.getIpAddress();
        }
        //返回值打印
        log.info("返回值ip地址" + ipAddress);
        return ipAddress;
    }


}
